package com.efounder.fragment;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnDismissListener;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.Bitmap;
import android.net.Uri;
import android.net.http.SslError;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import androidx.fragment.app.Fragment;
import androidx.appcompat.app.AlertDialog;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.webkit.CookieManager;
import android.webkit.DownloadListener;
import android.webkit.JsResult;
import android.webkit.SslErrorHandler;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.core.xml.StubObject;
import com.efounder.constant.EnvironmentVariable;
import com.efounder.frame.baseui.BaseFragment;
import com.efounder.frame.utils.OSPPlugin;
import com.efounder.ospmobilelib.R;
import com.efounder.util.LoadingDataUtilBlack;
import com.efounder.util.ToastUtil;
import com.efounder.utils.ResStringUtil;
import com.efounder.view.titlebar.AbTitleBar;
import com.efounder.widget.ESPWebView;
import com.pansoft.resmanager.ResFileManager;
import com.utilcode.util.UriUtils;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLDecoder;
import java.util.Hashtable;
import java.util.List;

public class SimpleWebFragmentNoRefreshNoForms extends BaseFragment {

    private static final String TAG = "SimpleWebFragment";
    private StubObject mMenuItem;
    private String titleStr;
    // CustomProgressDialog dialog;
    private View rootView;// 缓存Fragment view
    AbTitleBar title;
    ESPWebView web;
    Boolean isShowBottom;
    //FrameLayout fl;
    ImageView imageView;
    RelativeLayout include;
    boolean IsTitleVisible = true;
    String webUrl;
    com.pansoft.espcomp.ESPWebView wv;
    private boolean isPrepared;

    String directory;

    Context mContext;

    public SimpleWebFragmentNoRefreshNoForms(StubObject menuItem, String title) {
        this.mMenuItem = menuItem;
        this.titleStr = title;

    }

    public SimpleWebFragmentNoRefreshNoForms() {

    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {

        super.onActivityCreated(savedInstanceState);

    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        mContext = activity;
    }

    @Override
    public void onResume() {
        super.onResume();
        /*
         * TabBottomActivity menuFrag = TabBottomActivity.getInstance();
         * isShowBottom =
         * (menuFrag.getBottomBar().getVisibility()==View.VISIBLE);
         * if(isShowBottom) menuFrag.getBottomBar().setVisibility(View.GONE);
         */
    }

    @Override
    public void onStop() {
        super.onStop();
        /*
         * if(isShowBottom){ TabBottomActivity menuFrag =
         * TabBottomActivity.getInstance();
         * menuFrag.getBottomBar().setVisibility(View.VISIBLE); }
         */
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.normalwebview, container, false);
        Log.i("", "test===================onCreateView：--"
                + "SimpleWebFragmentNoRefreshNoForms");
        if (null != savedInstanceState) {
            mMenuItem = (StubObject) savedInstanceState.getSerializable("databack");
            titleStr = (String) savedInstanceState.getSerializable("title");
        } else {
            mMenuItem = (StubObject) getArguments().getSerializable("stubObject");
        }
        Hashtable menuTable = mMenuItem.getStubTable();
        webUrl = (String) menuTable.get("url");

        if (menuTable.containsKey("isLocalHtml")) {
            if ("1".equalsIgnoreCase((String) menuTable.get("isLocalHtml"))) {
//                webUrl = "file://" + Environment.getExternalStorageDirectory().getAbsolutePath()
//                        + "/"
//                        + EnvironmentVariable.getProperty(KEY_SETTING_APPID)
//                        + "/"
//                        + webUrl;
                webUrl = "file://" + ResFileManager.UNZIP_DIR + "/" + webUrl;
                ToastUtil.showToast(getActivity(), "路径：" + webUrl);
            }
        }
        String param = (String) menuTable.get("param");
        String value = (String) menuTable.get("value");
        if (param != null && value != null) {
            String[] paramStrings = param.split(";");
            String[] valueStrings = value.split(";");
            if (param != null) {
                for (int i = 0; i < paramStrings.length; i++) {
                    if (i == 0)
                        webUrl = webUrl + "?";
                    webUrl = webUrl + paramStrings[i] + "=" + valueStrings[i];
                    if (i != paramStrings.length - 1)
                        webUrl = webUrl + "&";
                }
            }
        }
        if (mMenuItem.getString("needUserName", "0").equals("1")) {
            webUrl = webUrl + EnvironmentVariable.getUserName();
        }
        String titleName = (String) menuTable.get("caption");
        // String contentView = (String)menuTable.get("contentView");
        // registerBoradcastReceiver();

        include = (RelativeLayout) rootView.findViewById(R.id.include);

//		if (IsTitleVisible) {
//			include.setVisibility(View.VISIBLE);
//		} else {
//			include.setVisibility(View.GONE);
//		}

        if (IsTitleVisible) {
            include.setVisibility(View.VISIBLE);
        } else {
            include.setVisibility(View.GONE);
        }

        if (isAlone()) {
            include.setVisibility(View.VISIBLE);
        } else {
            include.setVisibility(View.GONE);
        }


        TextView title = (TextView) rootView.findViewById(R.id.fragmenttitle);
        title.setText(titleName);
        LinearLayout leftbacklayout = (LinearLayout) rootView
                .findViewById(R.id.leftbacklayout);
        leftbacklayout.setVisibility(View.VISIBLE);

        leftbacklayout.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                getActivity().finish();

                //SimpleWebFragmentNoRefreshNoForms.this.getFragmentManager()
                //.popBackStack();
            }
        });

        Button buttonRight = (Button) rootView.findViewById(R.id.closeButton);
        buttonRight.setVisibility(View.INVISIBLE);
        buttonRight.setBackgroundResource(R.drawable.rightmenu);
        buttonRight.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // web.loadUrl("www.baidu.com");
                // new MonthWindows(SimpleWebFragment.this.getActivity(), v);
                /*
                 * final DateWindows dateWindows = new DateWindows(
                 * SimpleWebFragmentNoRefreshNoForms.this.getActivity(), v);
                 * dateWindows.setDateOnclickListener(new DateOnclickListener()
                 * {
                 *
                 * @Override public void ondateCalendarClick(String date) {
                 * dateWindows.dismiss(); //
                 * web.loadUrl("http://www.baidu.com"); } });
                 */
            }
        });

        /*
         * StringBuffer strUrl = null; // webUrl = "http://www.baidu.com"; if
         * (param != null&&false) { SharedPreferences share =
         * getActivity().getSharedPreferences( BaseApp.UserInfo,
         * Context.MODE_PRIVATE); // SharedPreferences sharedPreferences =
         * getActivity().getSharedPreferences(ESPApplication.UserInfo, //
         * //LoginSettingsActivity.SETTING_FILE, // Context.MODE_PRIVATE);
         *
         * String[] paramArr = param.split(";"); String[] valueArr =
         * value.split(";");
         *
         * String values = null; // 拼接url strUrl = new
         * StringBuffer().append(webUrl + "?");
         *
         * for (int i = 0; i < paramArr.length; i++) {
         *
         * //拼接& 第一个参数没有&符号 if(i >= 1){ strUrl = strUrl.append("&"); } // 拼接key
         * strUrl = strUrl.append(paramArr[i]); // 拼接= strUrl =
         * strUrl.append("=");
         *
         * // 拼接value values = valueArr[i]; if (values.equals("@USERNAME@")) {
         * values = share.getString(BaseApp.UserInfo_ID, "");
         *
         * } else if (values.equals("@PASSWORD@")) { values =
         * share.getString(BaseApp.UserInfo_PWD, "");
         *
         * } else if (values.equals("@AD@")) { values =
         * share.getString("dataFlag", "");
         *
         * } else if (values.equals("@EMAIL@")) { values =
         * share.getString(BaseApp.UserInfo_EMAIL, ""); } else if
         * (values.equals("@PHONENUMBER@")) { values =
         * share.getString(BaseApp.UserInfo_PHONENUMBER, ""); } strUrl =
         * strUrl.append(values); } webUrl = strUrl.toString(); }
         */
        // web = (ESPWebView) rootView.findViewById(R.id.mywebview);

        /*
         * FrameLayout fl = MyStaticWebView.getFl(); FrameLayout fl = new
         * FrameLayout(this.getActivity()); LayoutParams params = new
         * LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
         * fl.setLayoutParams(params); if(fl.getParent()!=null)
         * ((ViewGroup)fl.getParent()).removeAllViews();
         *
         * ImageView imageView = MyStaticWebView.getKuaiZhao();
         */
		/*fl = new FrameLayout(this.getActivity());
		LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT,
				LayoutParams.MATCH_PARENT);
		fl.setLayoutParams(params);*/
        // include.setVisibility(View.VISIBLE);
        // include.setVisibility(View.VISIBLE);
        wv = (com.pansoft.espcomp.ESPWebView) rootView
                .findViewById(R.id.mywebview);

        //允许JavaScript执行
        WebSettings webSettings = wv.getSettings();

        webSettings.setJavaScriptEnabled(true);

        webSettings.setDomStorageEnabled(true);
        webSettings.setDatabaseEnabled(true);
        webSettings.setAppCacheEnabled(true);
        //设置可以访问文件
        webSettings.setAllowFileAccess(true);
        wv.clearCache(true);

        /*
         * wv.setWebViewClient(new WebViewClient() { public boolean
         * shouldOverrideUrlLoading(WebView view, String url) { //
         * 重写此方法表明点击网页里面的链接还是在当前的webview里跳转，不跳到浏览器那边 view.loadUrl(url); return
         * true; } });
         */
        wv.setWebViewClient(new webClient());
        LayoutParams params1 = new LayoutParams(LayoutParams.MATCH_PARENT,
                LayoutParams.MATCH_PARENT);
        wv.setLayoutParams(params1);
        wv.setDownloadListener(new MyWebViewDownLoadListener());
        String username = EnvironmentVariable.getUserName();
        String userpass = EnvironmentVariable.getPassword();
        wv.addJavascriptInterface(new OSPPlugin(username, userpass, this), "OSPPlugin");
        /*
         * isPrepared = true; onVisible();
         */
        super.onCreateView(inflater, container, savedInstanceState);
        /*
         * if (getUserVisibleHint()) { //加载数据相当于Fragment的onPause lazyLoad(); }
         */
        // fl.addView(wv);
        return rootView;

        // fl.addView(wv);

        //

        /*
         * System.out.println(String.valueOf(webUrl));
         * web.loadUrl(String.valueOf(webUrl));
         */
        // return rootView;
    }

    private class webClient extends WebViewClient {

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            // dialog.show();
            view.loadUrl(url);
            return true;
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            LoadingDataUtilBlack.dismiss();
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);

            if (null != SimpleWebFragmentNoRefreshNoForms.this.getActivity())
                LoadingDataUtilBlack.show(SimpleWebFragmentNoRefreshNoForms.this
                        .getActivity());
        }

        public void onReceivedSslError(WebView view, SslErrorHandler handler,
                                       SslError error) {
            handler.proceed();// 接受证书
            LoadingDataUtilBlack.dismiss();
        }

    }

    @Override
    public void onStart() {
        /*
         * title = ((TabBottomActivity)getActivity()).getTitleBar();
         * title.setTitleText(titleStr); title.setVisibility(View.GONE);
         */
        super.onStart();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        // BroadCastutil.getinstance().unregisterWebBroadcastList((Context)SimpleWebFragmentNoRefresh.this.getActivity());
    }

    public void setTitleVisible(boolean IsTitleVisible1) {
        IsTitleVisible = IsTitleVisible1;

    }

    @Override
    public void onVisible() {
        // 当单独显示时，取消懒加载
        /*
         * if (!isAlone && (!isPrepared || !isVisible)) { return; }
         */
        wv.loadUrl(webUrl);
    }


    @Override
    public void onSaveInstanceState(Bundle outState) {
        // TODO Auto-generated method stub
        super.onSaveInstanceState(outState);
        outState.putSerializable("databack", mMenuItem);
        outState.putSerializable("title", titleStr);
    }

    //内部类
    private class MyWebViewDownLoadListener implements DownloadListener {


        @Override
        public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype,
                                    long contentLength) {
		        	/*if(!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
		        		Toast t=Toast.makeText(mContext, "需要SD卡。", Toast.LENGTH_LONG);
						t.setGravity(Gravity.CENTER, 0, 0);
						t.show();
						return;
		        	}*/
            directory = ResFileManager.DOWN_LOAD;
            File file = new File(directory);
            if (!file.exists() && !file.isDirectory()) {
                System.out.println("//不存在");
                file.mkdir();
            } else {
                System.out.println("//目录存在");
            }
            DownloaderTask task = new DownloaderTask();
            task.execute(url);
        }

    }

    //内部类
    private class DownloaderTask extends AsyncTask<String, Void, String> {

        public DownloaderTask() {
        }

        @Override
        protected String doInBackground(String... params) {
            // TODO Auto-generated method stubhttps://3g.zyof.com.cn:1445/msp.do?action=file-view@msp&do=download&url=http://pgoa.zyyt.sinopec.com/zyytpg/dep2715/swgl_2715.nsf/0/482579E80029146348257D6D003BA760/$file/HNX34FJLY8EGD80XAV8A.pdf&encoding=gbk
            String url = params[0];
//					Log.i("tag", "url="+url);
            url = url.substring(0, url.lastIndexOf("&encoding=gbk"));
            String fileName = url.substring(url.lastIndexOf("/") + 1);
            fileName = URLDecoder.decode(fileName);
            Log.i("tag", "fileName=" + fileName);

            //File directory=Environment.getExternalStorageDirectory();
            File file = new File(directory, fileName);
				/*	if(file.exists()){
						Log.i("tag", "The file has already exists.");
						return fileName;
					}*/
            try {
                DefaultHttpClient client = new DefaultHttpClient();
//		                client.getParams().setIntParameter("http.socket.timeout",3000);//设置超时
                HttpGet get = new HttpGet(url);


                String cookie = CookieManager.getInstance().getCookie(url);
                get.addHeader("cookie", cookie);
                HttpResponse response = client.execute(get);
                if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode()) {
                    HttpEntity entity = response.getEntity();
                    InputStream input = entity.getContent();

                    writeToSDCard(fileName, input);

                    input.close();
//							entity.consumeContent();
                    return fileName;
                } else {
                    return null;
                }
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
        }

        @Override
        protected void onCancelled() {
            // TODO Auto-generated method stub
            super.onCancelled();
        }

        @Override
        protected void onPostExecute(String result) {
            // TODO Auto-generated method stub
            super.onPostExecute(result);
            closeProgressDialog();
            if (result == null) {
                Toast t = Toast.makeText(mContext, ResStringUtil.getString(R.string.common_text_connect_error), Toast.LENGTH_LONG);
                t.setGravity(Gravity.CENTER, 0, 0);
                t.show();
                return;
            }

            Toast t = Toast.makeText(mContext, "已保存到SD卡。", Toast.LENGTH_LONG);
            t.setGravity(Gravity.CENTER, 0, 0);
            t.show();
            //File directory=Environment.getExternalStorageDirectory();
            File file = new File(directory, result);
            Log.i("tag", "Path=" + file.getAbsolutePath());

            try {
                Intent intent = getFileIntent(file);
                if (isIntentAvailable(mContext, intent)) {
                    mContext.startActivity(intent);
                } else {
                    Toast t1 = Toast.makeText(mContext, "请安装该文件类型的程序！", Toast.LENGTH_LONG);
                    t1.setGravity(Gravity.CENTER, 0, 0);
                    t1.show();
                }
            } catch (Exception e) {
                Toast t2 = Toast.makeText(mContext, "该文件打开失败，请检查手机是否存在打开该文件类型的程序。", Toast.LENGTH_LONG);
                t2.setGravity(Gravity.CENTER, 0, 0);
                t2.show();
            }


        }

        @Override
        protected void onPreExecute() {
            // TODO Auto-generated method stub
            super.onPreExecute();
            showProgressDialog();
        }

        @Override
        protected void onProgressUpdate(Void... values) {
            // TODO Auto-generated method stub
            super.onProgressUpdate(values);
        }


    }

    private ProgressDialog mDialog;

    private void showProgressDialog() {
        if (mDialog == null) {
            mDialog = new ProgressDialog(mContext);
            mDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);//设置风格为圆形进度条
            mDialog.setMessage(ResStringUtil.getString(R.string.common_text_please_wait));
            mDialog.setIndeterminate(false);//设置进度条是否为不明确
            mDialog.setCancelable(true);//设置进度条是否可以按退回键取消
            mDialog.setCanceledOnTouchOutside(false);
            mDialog.setOnDismissListener(new OnDismissListener() {


                @Override
                public void onDismiss(DialogInterface dialog) {
                    // TODO Auto-generated method stub
                    mDialog = null;
                }
            });
            mDialog.show();

        }
    }

    private void closeProgressDialog() {
        if (mDialog != null) {
            mDialog.dismiss();
            mDialog = null;
        }
    }

    public Intent getFileIntent(File file) {
        //       Uri uri = Uri.parse("http://m.ql18.com.cn/hpf10/1.pdf");
        Uri uri = UriUtils.getUriForFile(file);
        String type = getMIMEType(file);
        Log.i("tag", "type=" + type);
        Intent intent = new Intent("android.intent.action.VIEW");
        intent.addCategory("android.intent.category.DEFAULT");
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        intent.setDataAndType(uri, type);
        return intent;
    }

    public void writeToSDCard(String fileName, InputStream input) {

        //   if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
        // File directory=Environment.getExternalStorageDirectory();
        File file = new File(directory, fileName);
        //          if(file.exists()){
        //              Log.i("tag", "The file has already exists.");
        //              return;
        //          }
        try {
            FileOutputStream fos = new FileOutputStream(file);
            byte[] b = new byte[2048];
            int j = 0;
            while ((j = input.read(b)) != -1) {
                fos.write(b, 0, j);
            }
            fos.flush();
            fos.close();
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
		           /* }else{   
		                Log.i("tag", "NO SDCard.");   
		            }*/
    }

    private String getMIMEType(File f) {
        String type = "";
        String fName = f.getName();
        /* 取得扩展名 */
        String end = fName.substring(fName.lastIndexOf(".") + 1, fName.length()).toLowerCase();

        /* 依扩展名的类型决定MimeType */
        if (end.equals("pdf")) {
            type = "application/pdf";//
        } else if (end.equals("m4a") || end.equals("mp3") || end.equals("mid") ||
                end.equals("xmf") || end.equals("ogg") || end.equals("wav")) {
            type = "audio/*";
        } else if (end.equals("3gp") || end.equals("mp4")) {
            type = "video/*";
        } else if (end.equals("jpg") || end.equals("gif") || end.equals("png") ||
                end.equals("jpeg") || end.equals("bmp")) {
            type = "image/*";
        } else if (end.equals("apk")) {
            /* android.permission.INSTALL_PACKAGES */
            type = "application/vnd.android.package-archive";
        } else if (end.equals("pptx") || end.equals("ppt")) {
            type = "application/vnd.ms-powerpoint";
        } else if (end.equals("docx") || end.equals("doc")) {
            type = "application/msword";
        } else if (end.equals("xlsx") || end.equals("xls")) {
            type = "application/vnd.ms-excel";
        } else {
            //        /*如果无法直接打开，就跳出软件列表给用户选择 */
            type = "*/*";
        }
        return type;
    }

    /**
     * 判断Intent 是否存在 防止崩溃
     *
     * @param context
     * @param intent
     * @return
     */
    private boolean isIntentAvailable(Context context, Intent intent) {
        final PackageManager packageManager = context.getPackageManager();
        List<ResolveInfo> list = packageManager.queryIntentActivities(intent,
                PackageManager.GET_ACTIVITIES);
        return list.size() > 0;
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            if (data != null) {
                String msg = data.getStringExtra("scanResult");
//                JSONObject jsonObject = JSONObject.fromObject(msg);
//                String resultData = jsonObject.optString("data", "");
                final String method = "javascript:setScanResult(\'" + msg + "\')";
                wv.post(new Runnable() {
                    @Override
                    public void run() {
                        wv.loadUrl(method);
                    }
                });
            }

        }else   if (requestCode == Controller.FILE_SELECTED) {
            // Chose a file from the file picker.
            if (mUploadHandler != null) {
                mUploadHandler.onResult(resultCode, data);
            }
        }
    }


    UploadHandler mUploadHandler;

    class MyWebChromeClient extends WebChromeClient {
        public MyWebChromeClient() {

        }

        private String getTitleFromUrl(String url) {
            String title = url;
            try {
                URL urlObj = new URL(url);
                String host = urlObj.getHost();
                if (host != null && !host.isEmpty()) {
                    return urlObj.getProtocol() + "://" + host;
                }
                if (url.startsWith("file:")) {
                    String fileName = urlObj.getFile();
                    if (fileName != null && !fileName.isEmpty()) {
                        return fileName;
                    }
                }
            } catch (Exception e) {
                // ignore
            }

            return title;
        }

        @Override
        public boolean onJsAlert(WebView view, String url, String message, final JsResult result) {
            String newTitle = getTitleFromUrl(url);

            new AlertDialog.Builder(mContext).setTitle(newTitle).setMessage(message).setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    result.confirm();
                }
            }).setCancelable(false).create().show();
            return true;
            // return super.onJsAlert(view, url, message, result);
        }

        @Override
        public boolean onJsConfirm(WebView view, String url, String message, final JsResult result) {

            String newTitle = getTitleFromUrl(url);

            new AlertDialog.Builder(mContext).setTitle(newTitle).setMessage(message).setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    result.confirm();
                }
            }).setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    result.cancel();
                }
            }).setCancelable(false).create().show();
            return true;

            // return super.onJsConfirm(view, url, message, result);
        }

        // Android 2.x
        public void openFileChooser(ValueCallback<Uri> uploadMsg) {
            openFileChooser(uploadMsg, "");
        }

        // Android 3.0
        public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
            openFileChooser(uploadMsg, "", "filesystem");
        }

        // Android 4.1
        public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
            mUploadHandler = new UploadHandler(new Controller());
            mUploadHandler.openFileChooser(uploadMsg, acceptType, capture);
        }

        // Android 4.4, 4.4.1, 4.4.2
        // openFileChooser function is not called on Android 4.4, 4.4.1, 4.4.2,
        // you may use your own java script interface or other hybrid framework.

        // Android 5.0.1
        @SuppressLint("NewApi")
        public boolean onShowFileChooser(
                WebView webView, ValueCallback<Uri[]> filePathCallback,
                FileChooserParams fileChooserParams) {

            String acceptTypes[] = fileChooserParams.getAcceptTypes();

            String acceptType = "";
            for (int i = 0; i < acceptTypes.length; ++i) {
                if (acceptTypes[i] != null && acceptTypes[i].length() != 0)
                    acceptType += acceptTypes[i] + ";";
            }
            if (acceptType.length() == 0)
                acceptType = "*/*";

            final ValueCallback<Uri[]> finalFilePathCallback = filePathCallback;

            ValueCallback<Uri> vc = new ValueCallback<Uri>() {

                @Override
                public void onReceiveValue(Uri value) {

                    Uri[] result;
                    if (value != null)
                        result = new Uri[]{value};
                    else
                        result = null;

                    finalFilePathCallback.onReceiveValue(result);

                }
            };

            openFileChooser(vc, acceptType, "filesystem");


            return true;
        }
    }

    ;

    class Controller {
        final static int FILE_SELECTED = 4;

        Activity getActivity() {
            return (Activity) mContext;
        }
    }

    /**
     * 得到根Fragment
     *
     * @return
     */
    private Fragment getRootFragment() {
        Fragment fragment = getParentFragment();
        if (fragment == null) return this;
        while (fragment.getParentFragment() != null) {
            fragment = fragment.getParentFragment();
        }
        return fragment;
    }

    class UploadHandler {
        /*
         * The Object used to inform the WebView of the file to upload.
         */
        private ValueCallback<Uri> mUploadMessage;
        private String mCameraFilePath;
        private boolean mHandled;
        private boolean mCaughtActivityNotFoundException;
        private Controller mController;

        public UploadHandler(Controller controller) {
            mController = controller;
        }

        String getFilePath() {
            return mCameraFilePath;
        }

        boolean handled() {
            return mHandled;
        }

        void onResult(int resultCode, Intent intent) {
            if (resultCode == Activity.RESULT_CANCELED && mCaughtActivityNotFoundException) {
                // Couldn't resolve an activity, we are going to try again so skip
                // this result.
                mCaughtActivityNotFoundException = false;
                return;
            }
            Uri result = intent == null || resultCode != Activity.RESULT_OK ? null
                    : intent.getData();
            // As we ask the camera to save the result of the user taking
            // a picture, the camera application does not return anything other
            // than RESULT_OK. So we need to check whether the file we expected
            // was written to disk in the in the case that we
            // did not get an intent returned but did get a RESULT_OK. If it was,
            // we assume that this result has came back from the camera.
            if (result == null && intent == null && resultCode == Activity.RESULT_OK) {
                File cameraFile = new File(mCameraFilePath);
                if (cameraFile.exists()) {
                    result = Uri.fromFile(cameraFile);
                    // Broadcast to the media scanner that we have a new photo
                    // so it will be added into the gallery for the user.
                    mController.getActivity().sendBroadcast(
                            new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, result));
                }
            }
            mUploadMessage.onReceiveValue(result);
            mHandled = true;
            mCaughtActivityNotFoundException = false;
        }

        void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
            final String imageMimeType = "image/*";
            final String videoMimeType = "video/*";
            final String audioMimeType = "audio/*";
            final String mediaSourceKey = "capture";
            final String mediaSourceValueCamera = "camera";
            final String mediaSourceValueFileSystem = "filesystem";
            final String mediaSourceValueCamcorder = "camcorder";
            final String mediaSourceValueMicrophone = "microphone";
            // According to the spec, media source can be 'filesystem' or 'camera' or 'camcorder'
            // or 'microphone' and the default value should be 'filesystem'.
            String mediaSource = mediaSourceValueFileSystem;
            if (mUploadMessage != null) {
                // Already a file picker operation in progress.
                return;
            }
            mUploadMessage = uploadMsg;
            // Parse the accept type.
            String params[] = acceptType.split(";");
            String mimeType = params[0];
            if (capture.length() > 0) {
                mediaSource = capture;
            }
            if (capture.equals(mediaSourceValueFileSystem)) {
                // To maintain backwards compatibility with the previous implementation
                // of the media capture API, if the value of the 'capture' attribute is
                // "filesystem", we should examine the accept-type for a MIME type that
                // may specify a different capture value.
                for (String p : params) {
                    String[] keyValue = p.split("=");
                    if (keyValue.length == 2) {
                        // Process key=value parameters.
                        if (mediaSourceKey.equals(keyValue[0])) {
                            mediaSource = keyValue[1];
                        }
                    }
                }
            }
            //Ensure it is not still set from a previous upload.
            mCameraFilePath = null;
            if (mimeType.equals(imageMimeType)) {
                if (mediaSource.equals(mediaSourceValueCamera)) {
                    // Specified 'image/*' and requested the camera, so go ahead and launch the
                    // camera directly.
                    startActivity(createCameraIntent());
                    return;
                } else {
                    // Specified just 'image/*', capture=filesystem, or an invalid capture parameter.
                    // In all these cases we show a traditi picker filetered on accept type
                    // so launch an intent for both the Camera onaland image/* OPENABLE.
                    Intent chooser = createChooserIntent(createCameraIntent());
                    chooser.putExtra(Intent.EXTRA_INTENT, createOpenableIntent(imageMimeType));
                    startActivity(chooser);
                    return;
                }
            } else if (mimeType.equals(videoMimeType)) {
                if (mediaSource.equals(mediaSourceValueCamcorder)) {
                    // Specified 'video/*' and requested the camcorder, so go ahead and launch the
                    // camcorder directly.
                    startActivity(createCamcorderIntent());
                    return;
                } else {
                    // Specified just 'video/*', capture=filesystem or an invalid capture parameter.
                    // In all these cases we show an intent for the traditional file picker, filtered
                    // on accept type so launch an intent for both camcorder and video/* OPENABLE.
                    Intent chooser = createChooserIntent(createCamcorderIntent());
                    chooser.putExtra(Intent.EXTRA_INTENT, createOpenableIntent(videoMimeType));
                    startActivity(chooser);
                    return;
                }
            } else if (mimeType.equals(audioMimeType)) {
                if (mediaSource.equals(mediaSourceValueMicrophone)) {
                    // Specified 'audio/*' and requested microphone, so go ahead and launch the sound
                    // recorder.
                    startActivity(createSoundRecorderIntent());
                    return;
                } else {
                    // Specified just 'audio/*',  capture=filesystem of an invalid capture parameter.
                    // In all these cases so go ahead and launch an intent for both the sound
                    // recorder and audio/* OPENABLE.
                    Intent chooser = createChooserIntent(createSoundRecorderIntent());
                    chooser.putExtra(Intent.EXTRA_INTENT, createOpenableIntent(audioMimeType));
                    startActivity(chooser);
                    return;
                }
            }
            // No special handling based on the accept type was necessary, so trigger the default
            // file upload chooser.
            startActivity(createDefaultOpenableIntent());
        }

        private void startActivity(Intent intent) {
            try {
                getRootFragment().startActivityForResult(intent, Controller.FILE_SELECTED);
            } catch (ActivityNotFoundException e) {
                // No installed app was able to handle the intent that
                // we sent, so fallback to the default file upload control.
                try {
                    mCaughtActivityNotFoundException = true;
                    getRootFragment().startActivityForResult(createDefaultOpenableIntent(),
                            Controller.FILE_SELECTED);
                } catch (ActivityNotFoundException e2) {
                    // Nothing can return us a file, so file upload is effectively disabled.
                    Toast.makeText(mController.getActivity(), "....",
                            Toast.LENGTH_LONG).show();
                }
            }
        }

        private Intent createDefaultOpenableIntent() {
            // Create and return a chooser with the default OPENABLE
            // actions including the camera, camcorder and sound
            // recorder where available.
            Intent i = new Intent(Intent.ACTION_GET_CONTENT);
            i.addCategory(Intent.CATEGORY_OPENABLE);
            i.setType("*/*");
            Intent chooser = createChooserIntent(createCameraIntent(), createCamcorderIntent(),
                    createSoundRecorderIntent());
            chooser.putExtra(Intent.EXTRA_INTENT, i);
            return chooser;
        }

        private Intent createChooserIntent(Intent... intents) {
            Intent chooser = new Intent(Intent.ACTION_CHOOSER);
            chooser.putExtra(Intent.EXTRA_INITIAL_INTENTS, intents);
            chooser.putExtra(Intent.EXTRA_TITLE, "选择文件");
            return chooser;
        }

        private Intent createOpenableIntent(String type) {
            Intent i = new Intent(Intent.ACTION_GET_CONTENT);
            i.addCategory(Intent.CATEGORY_OPENABLE);
            i.setType(type);
            return i;
        }

        private Intent createCameraIntent() {
            Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            File externalDataDir = Environment.getExternalStoragePublicDirectory(
                    Environment.DIRECTORY_DCIM);
            File cameraDataDir = new File(externalDataDir.getAbsolutePath() +
                    File.separator + "browser-photos");
            cameraDataDir.mkdirs();
            mCameraFilePath = cameraDataDir.getAbsolutePath() + File.separator +
                    System.currentTimeMillis() + ".jpg";
            cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(mCameraFilePath)));
            return cameraIntent;
        }

        private Intent createCamcorderIntent() {
            return new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
        }

        private Intent createSoundRecorderIntent() {
            return new Intent(MediaStore.Audio.Media.RECORD_SOUND_ACTION);
        }
    }



}
